package mall.demo.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mall.demo.mybatis.pojo.Product;
import mall.demo.mybatis.pojo.ProductInCart;
import mall.demo.mybatis.service.ProductService;
import mall.demo.util.SessionKeyEnum;

@WebServlet("/servlet/delcart.do")
public class DelCartServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		int productId = 0;
		try {
			productId = Integer.parseInt(req.getParameter("id"));
		} catch (NumberFormatException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		Product prod = (new ProductService()).getProductById(productId);
		List<ProductInCart> carts = (List<ProductInCart>)req.getSession().getAttribute(SessionKeyEnum.cart.name());
		ProductInCart foundProd = null;
		for(ProductInCart p : carts) {
			if(p.getProductId() == prod.getProductId()) {
				carts.remove(p);
				break;
			}
		}
		resp.sendRedirect(req.getContextPath()+"/cart.jsp");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		doGet(req, resp);
	}

}
